"""
@Author: Shan ZhengFei
@Date: 2024-11-22
@Version: 1.0
@Description: 每日晚安脚本，用于向指定用户发送天气和问候信息。
@Copyright: © 2023 Shan ZhengFei. All rights reserved.
"""
import random
import requests
import logging
from datetime import datetime, timedelta

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 微信企业id
WECHAT_CORPID = "wwcb0xxxxxxxx737d"
# secret
WECHAT_CORPSECRET = "s8kFpC02xxxxxxxxv17lQYFzNCA4"
# 接收者
WECHAT_TOUSER = "User1|User2"
# 应用id
WECHAT_AGENTID = "1000001"
# 彩云天气token
CAIYUN_TOKEN = "qHi1TzxxxxxxxxWwzPAH"
# 天气城市
CAIYUN_LOCATION = "118.715,32.1077"
# 黄历key
HUANG_LI_KEY = "929be8axxxxxxxxe1ed09c8f8e"

# URL常量
GET_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}"
SEND_MSG_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}"
CAI_YUN_URL = "https://api.caiyunapp.com/v2.5/{}/{}/daily.json"
YI_YAN_URL = "https://international.v1.hitokoto.cn/?c=k"
HUANG_LI_URL = "http://v.juhe.cn/laohuangli/d?date={}&key={}"
ONE_WORD_URL = "https://api.xygeng.cn/openapi/one"

# 信息常量
TITLE = "亲爱的老婆，喜欢有你的每一天，晚安🌙"
DESCRIPTION_TEMPLATE = (
    "📅 明天是：{today}\n"
    "📜 农历：{yinLi}\n"
    "🌤️ 明天天气：南京 {weather}\n"
    "👔 穿衣：{clothingAdvice}\n"
    "🎏 今日哲语：{zheyu}\n"
    "💬 晚安语：{words}\n"
)
# 点击跳转url
URL = "https://api.03c3.cn/api/zb"
# 图片url
PIC_URL = "https://pic.imgdb.cn/item/6745b21bd0e0a243d4d16a1b.webp"

# 获取企微应用发送消息token
def get_access_token():
    url = GET_TOKEN_URL.format(WECHAT_CORPID, WECHAT_CORPSECRET)
    response = requests.get(url)
    data = response.json()

    if data.get("errcode") == 0:
        logger.info("获取 Access Token 成功")
        return data.get("access_token")
    else:
        logger.error("获取 Access Token 失败: %s", data.get("errmsg", "未知错误"))
        return None

# 发送每日问候
def send_daily_greeting():
    access_token = get_access_token()
    if not access_token:
        return

    url = SEND_MSG_URL.format(access_token)

    # 获取天气信息
    weather_response = get_weather()
    daily = weather_response.get("result", {}).get("daily", {})
    temperature = daily.get("temperature", [{}])[1]
    skycon = daily.get("skycon", [{}])[1].get("value", "")

    # 映射天气描述
    weather_desc = map_skycon_to_description(skycon)

    # 获取穿衣建议
    clothing_advice = get_clothing_advice(temperature.get("max", 0))

    # 获取每日一言
    hitokoto = get_yiyan()

    # 获取黄历信息
    huangli_response = get_huangli()
    huangli = huangli_response.get("result", {})

    # 动态生成 description 内容并替换占位符
    description = DESCRIPTION_TEMPLATE.format(
        today=get_tomorrow(),
        weather=f"{weather_desc} {round(temperature.get('min', 0))} ~ {round(temperature.get('max', 0))} ℃",
        clothingAdvice=clothing_advice,
        yinLi=huangli.get("yinli", ""),
        words=get_random_sentence() + "好梦小青青老婆~",
        zheyu=hitokoto.get("hitokoto", "") + "--" + hitokoto.get("from", "")
    )

    # 构建消息请求
    request_data = {
        "touser": WECHAT_TOUSER,
        "msgtype": "news",
        "agentid": WECHAT_AGENTID,
        "news": {
            "articles": [
                {
                    "title": TITLE,
                    "description": description,
                    "url": URL,
                    "picurl": PIC_URL
                }
            ]
        }
    }
    logger.info("发送消息信息: %s", description)
    response = requests.post(url, json=request_data)
    if response.status_code == 200:
        logger.info("发送消息成功 返回信息: %s", response.text)
    else:
        logger.error("发送失败")

# 获取彩云天气信息
def get_weather():
    url = CAI_YUN_URL.format(CAIYUN_TOKEN, CAIYUN_LOCATION)
    response = requests.get(url)
    data = response.json()

    if data.get("status") == "ok":
        logger.info("获取彩云天气信息成功")
        return data
    else:
        logger.error("获取彩云天气信息失败")
        raise Exception("获取彩云天气信息失败")

# 映射彩云天气状况描述
def map_skycon_to_description(skycon):
    skycon_map = {
        "CLEAR_DAY": "晴",
        "CLEAR_NIGHT": "晴",
        "PARTLY_CLOUDY_DAY": "多云",
        "PARTLY_CLOUDY_NIGHT": "多云",
        "CLOUDY": "阴",
        "LIGHT_HAZE": "轻度雾霾",
        "MODERATE_HAZE": "中度雾霾",
        "HEAVY_HAZE": "重度雾霾",
        "LIGHT_RAIN": "小雨",
        "MODERATE_RAIN": "中雨",
        "HEAVY_RAIN": "大雨",
        "STORM_RAIN": "暴雨",
        "FOG": "雾",
        "LIGHT_SNOW": "小雪",
        "MODERATE_SNOW": "中雪",
        "HEAVY_SNOW": "大雪",
        "STORM_SNOW": "暴雪",
        "DUST": "浮尘",
        "SAND": "沙尘",
        "WIND": "大风"
    }
    return skycon_map.get(skycon, "未知天气")

# 获取黄历信息
def get_huangli():
    url = HUANG_LI_URL.format(get_tomorrow(), HUANG_LI_KEY)
    response = requests.get(url)
    data = response.json()

    if data:
        logger.info("获取黄历成功")
        return data
    else:
        logger.error("获取黄历失败")
        raise Exception("获取黄历失败")

# 自定义穿衣建议
def get_clothing_advice(max_temp):
    if max_temp <= -10:
        return "长款厚羽绒服、毛衣。"
    elif max_temp < 0:
        return "厚羽绒服、毛衣。"
    elif max_temp < 10:
        return "厚毛衣、风衣或夹克。"
    elif max_temp < 15:
        return "中等厚度毛衣或卫衣、长裤。"
    elif max_temp < 20:
        return "长袖衬衫、薄外套、长裤。"
    elif max_temp < 25:
        return "短袖衬衫T恤、薄长裤。"
    elif max_temp < 30:
        return "短袖衬衫T恤、短裤短裙。"
    else:
        return "短袖T恤、短裤或短裙。"

# 获取明天的日期
def get_tomorrow():
    tomorrow = datetime.now() + timedelta(days=1)
    week_day_map = {
        0: "一",
        1: "二",
        2: "三",
        3: "四",
        4: "五",
        5: "六",
        6: "日"
    }
    week_day = week_day_map[tomorrow.weekday()]
    return tomorrow.strftime(f"%Y-%m-%d 星期{week_day}")

# 获取每日一言
def get_yiyan():
    response = requests.get(YI_YAN_URL)
    data = response.json()

    if data:
        logger.info("获取每日一言成功")
        return data
    else:
        logger.error("获取每日一言失败")
        raise Exception("获取每日一言失败")

# 定义包含 80 句话的列表
sentences = [
    "愿月光温柔，伴你好梦。",
    "星辰入梦，一夜安眠。",
    "好梦连连，明日精神满满。",
    "夜色已深，愿你枕着星河入梦。",
    "今夜无烦忧，醒来是晴天。",
    "晚风拂面，带去我对你深深的祝福。",
    "睡个好觉，明天的太阳依旧温暖。",
    "昼解不开的结，黑夜慢慢耗。",
    "累了就睡吧，梦里啥都有。",
    "愿你梦里能抵达所有未至的远方。",
    "月亮偷偷吻着星星，而我在梦里想你。",
    "明天又是新的一天，晚安，世界。",
    "晚安，换个世界想你，一会儿见。",
    "闭眼是梦，睁眼是你，晚安。",
    "愿你的梦里，有梦可栖，有树可依。",
    "人间已无暇顾及，唯愿夜夜好眠。",
    "月亮不睡我不睡，我是人间小美味，晚安哦。",
    "晚安，愿长夜无梦，在所有夜晚都安眠。",
    "今夜星光灿烂，适合好梦连连。",
    "愿你梦中有玫瑰，醒来有希望。",
    "夜幕降临，心随星动，晚安好梦。",
    "星河滚烫，你是人间理想，晚安。",
    "月亮溺死在爱河，星星得不到爱火，晚安。",
    "愿你以梦为马，不负韶华，晚安。",
    "与你道一声晚安，望你一切安好。",
    "忘掉白天的忙碌，让心灵沉静，晚安。",
    "睡吧，待醒来时，又是满血复活的一天。",
    "今夜，星河璀璨，我以星语心愿，祝你晚安。",
    "愿你夜夜都好梦，天天是晴天。",
    "睡觉吧，梦里啥都有，比如明天的早餐。",
    "繁星点点，伴你安然入眠，好梦。",
    "晚安，是换个世界想你。",
    "闭上眼睛，把一天的好心情酝酿成一坛美梦。",
    "晚风轻拂，星河若梦，晚安。",
    "夜色温柔，而你更甚，晚安。",
    "岁月静好，安然入梦，晚安。",
    "月亮掉海里，今晚海底捞，晚安。",
    "人生如梦，梦里花开，晚安。",
    "夜深了，人静了，该睡了，晚安。",
    "星河滚烫，你是人间理想；夜色温柔，你是人间绝色，晚安。",
    "与世界道声晚安，与自己说声感谢。",
    "愿你有好梦相随，不再失眠。",
    "晚风轻唱，星月入梦，好梦连连。",
    "晚安，愿你梦里有诗，醒来有远方。",
    "梦里有你，香甜无比，晚安。",
    "愿你梦中有我，醒来有微笑，晚安。",
    "愿你每个梦里，都有笑容，晚安。",
    "夜色正好，适合入梦，晚安。",
    "星星眨眼，是我对你道的晚安。",
    "晚安，愿你带着好心情入睡，做个好梦。",
    "睡眠是门艺术，谁也无法阻挡我追求艺术的脚步，晚安！",
    "晚安，愿长夜无梦，梦里有你。",
    "月亮偷偷钻进了云的怀里，你多久才能钻进我的被窝里？",
    "愿你所得皆所期，所失亦无碍，晚安。",
    "愿你梦里星河灿烂，醒来岁月静好，晚安。",
    "愿你梦里有星辰，醒来有光明，晚安。",
    "今夜星光月光，都不及你眼里的光，晚安。",
    "星河滚烫，人间理想，晚安好梦。",
    "月亮不营业，我来对你说晚安。",
    "夜幕低垂，愿你今夜无梦，好眠。",
    "愿你梦里花落知多少，晚安。",
    "夜已深，愿你枕边有人，梦里有光，晚安。",
    "星河滚烫，你是人间理想，晚安，好梦。",
    "晚安，愿你梦里花开，醒来遇见更美好的自己。",
    "夜色已深，放下一天的疲惫，进入甜美的梦乡。",
    "愿你夜夜好梦相随，醒来皆是美好。",
    "晚安，愿你带着幸福的微笑，甜甜入睡。",
    "晚风轻拂，星月交辉，愿你今夜好梦。",
    "愿你今夜无愁，明早有粥，晚安。",
    "晚安，愿你梦里有星辰大海，醒来有日出云霞。",
    "闭上眼，让梦开始飞行，晚安。",
    "晚安，愿你今夜无梦，有个甜蜜的睡眠。",
    "愿你梦里有彩虹，醒来有远方，晚安。",
    "夜深人静，愿你安然入睡，美梦相伴。",
    "愿你梦中所想，醒来都能实现，晚安。",
    "星河滚烫，你是人间理想，夜色温柔，你是人间绝色，晚安。",
    "晚安，愿你忘记今日的烦恼，迎接明天的美好。",
    "愿你今夜好梦，梦里有我，晚安。",
    "晚安，愿你梦里有歌，醒来有笑。",
    "月亮不睡我不睡，但愿我是第一个说晚安给你的人。"
]

# 随机获取一句话
def get_random_sentence():
    return random.choice(sentences)

if __name__ == "__main__":
    send_daily_greeting()